package org.dromara.quick.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.dromara.common.core.utils.IdGenerator;
import org.dromara.common.heweather.constant.CacheConstants;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.quick.chat.domain.UserIpLocation;
import org.dromara.quick.chat.service.UserIpLocationService;
import org.dromara.quick.chat.mapper.UserIpLocationMapper;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
* @author Stars
* @description 针对表【user_ip_location(存储用户 IP 地址及其对应的属地信息)】的数据库操作Service实现
* @createDate 2025-03-06 22:12:27
*/
@Service
public class UserIpLocationServiceImpl extends ServiceImpl<UserIpLocationMapper, UserIpLocation>
    implements UserIpLocationService{

    @Override
    public int insertOrUpdateUserIpLocation(UserIpLocation userIpLocation) {
        userIpLocation.setId(IdGenerator.getId());
        return baseMapper.insertOrUpdateUserIpLocation(userIpLocation);
    }

    @Override
    public String selectUserIpLocationByUserId(Long userId) {
        String cacheObject = RedisUtils.getCacheObject(CacheConstants.CACHE_USER_IP_LOCATION_KEY + userId);
        if (StringUtils.isNotEmpty(cacheObject)){
            return cacheObject;
        }
        UserIpLocation userIpLocation = baseMapper.selectOne(new LambdaQueryWrapper<UserIpLocation>().select(UserIpLocation::getIpLocation).eq(UserIpLocation::getUserId, userId));
        if (userIpLocation == null){
            return null;
        }
        RedisUtils.setCacheObject(CacheConstants.CACHE_USER_IP_LOCATION_KEY+userId, userIpLocation.getIpLocation(), Duration.ofHours(3));
        return userIpLocation.getIpLocation();
    }
}




